﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EMoney.IStock.Client.Business.JRPT;
using EMoney.IStock.Client.Framework;
using EMoney.IStock.Client.Models.QQ;
using QConnectSDK;
using QConnectSDK.Context;

namespace EMoney.IStock.Client.Web.Controllers
{
    public class OAuthController : Controller
    {
        public ActionResult QQ(string returnURL)
        {
            if (string.IsNullOrEmpty(Request["code"]))
            {
                var context = new QzoneContext();
                string state = Guid.NewGuid().ToString().Replace("-", "");
                Session["requeststate"] = state;
                string scope = "get_user_info,add_share,list_album,upload_pic,check_page_fans,add_t,add_pic_t,del_t,get_repost_list,get_info,get_other_info,get_fanslist,get_idolist,add_idol,del_idol,add_one_blog,add_topic,get_tenpay_addr";

                string authenticationUrl = context.GetAuthorizationUrl(state, scope);
                authenticationUrl = string.Format(authenticationUrl, Server.UrlEncode(returnURL));

                return new RedirectResult(authenticationUrl);
            }
            else
            {
                var verifierCode = Request["code"];
                var state = Request["state"];
                var returnUrl = Request["returnUrl"];

                ViewBag.Code = verifierCode;

                if (!string.IsNullOrEmpty(verifierCode))
                {
                    returnUrl = string.Concat(returnUrl, "&openid=", verifierCode);
                }

                return Redirect(returnUrl);

                if (!string.IsNullOrEmpty(returnUrl) && !string.IsNullOrEmpty(verifierCode))
                {
                    if (returnUrl.IndexOf("bind|", StringComparison.OrdinalIgnoreCase) > -1)
                    {
                        string[] arrBindInfo = returnUrl.Split('|');

                        if (arrBindInfo.Length == 2)
                        {
                            ViewBag.BindUserID = arrBindInfo[1];
                        }
                    }
                    else
                    {
                        return UserIDAction(verifierCode, RegLoginType.QQ, returnUrl);
                    }

                    //QOpenClient qzone = new QOpenClient(verifierCode, string.Empty);
                    //var currentUser = qzone.GetCurrentUser();

                    //ViewBag.ReturnUrl = Request["returnUrl"];
                    //ViewBag.Nickname = currentUser.Nickname;
                }

                return View();
            }
        }

        public ActionResult qqshow()
        {
            QOpenClient qzone = null;

            var verifierCode = Request["code"];

            string result = string.Empty;

            try
            {
                qzone = new QOpenClient(verifierCode, string.Empty);
                var currentUser = qzone.GetCurrentUser();
                currentUser.Figureurl = currentUser.Figureurl.Substring(0, currentUser.Figureurl.LastIndexOf("/")) + "/100";

                result = string.Concat("OpenId:", qzone.OAuthToken.OpenId, "  AccessToken:", qzone.OAuthToken.AccessToken,
                    "  Nickname:", currentUser.Nickname, "  Figureurl:", currentUser.Figureurl);

                //return OAuthLoginAction("QQ", qzone.OAuthToken.OpenId, qzone.OAuthToken.AccessToken, currentUser.Nickname, returnURL, string.Empty);
            }
            catch (Exception ex)
            {
                result = string.Concat("异常：", ex.Message);
                //LogManager.DefaultLogger.Error(LogConvert.ParseWebEx(ex), "OAuth/QQ发生异常");

                //return Redirect(Url.Action("index", "home"));
            }

            ViewBag.Result = result;

            return View();
        }

        public ActionResult UserIDAction(string code, RegLoginType regLoginType, string returnUrl)
        {
            string uniqueNo = string.Empty;
            ReqLogin regLogin = new ReqLogin()
            {
                userType = regLoginType.GetHashCode(),
                account = code,
                clientType = 2
            };

            OAuthBll oAuthBll = new OAuthBll();

            LoginResult loginResult = oAuthBll.GetLoginResult(regLogin);

            if (loginResult != null && loginResult.id != 0)
            {
                uniqueNo = StringHelper.GetUniqueNo();

                if (!string.IsNullOrEmpty(uniqueNo))
                {
                    uniqueNo = uniqueNo.PadRight(16, '0');
                    JRPTCommCache.AddCache<string>(uniqueNo, loginResult.id.ToString(), 30);
                }

                string redirectUrl = string.Empty;

                if (returnUrl.IndexOf("?") > -1)
                {
                    redirectUrl = string.Concat(returnUrl, "&gid=", uniqueNo);
                }
                else
                {
                    redirectUrl = string.Concat(returnUrl, "?gid=", uniqueNo);
                }

                if (!string.IsNullOrEmpty(regLogin.OpenID))
                {
                    redirectUrl = string.Concat(redirectUrl, "&openid=", regLogin.OpenID);
                }

                return Redirect(redirectUrl);
            }

            return null;
        }

    }
}
